/**
 * jims
 */
package com.jims.master.modules.doctor.service;

import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.LongTextToString;
import com.jims.master.common.utils.NumberUtils;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.csm.dao.ExpStockDao;
import com.jims.master.modules.csm.entity.ExpStock;
import com.jims.master.modules.csm.service.ExpStockService;
import com.jims.master.modules.doctor.dao.*;
import com.jims.master.modules.doctor.entity.*;
import com.jims.master.modules.doctor.vo.SaveDataVo;
import com.jims.master.modules.finance.service.OutpRcptMasterService;
import com.jims.master.modules.oper.dao.ClinicItemDictDao;
import com.jims.master.modules.oper.dao.ClinicVsChargeDao;
import com.jims.master.modules.oper.entity.ClinicItemDict;
import com.jims.master.modules.oper.service.ClinicItemDictService;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.dao.OrgDeptDao;
import com.jims.master.modules.sys.entity.Company;
import com.jims.master.modules.sys.entity.OrgDept;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.template.dao.TreatProjectItemDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 处置治疗Service
 * @author 陈晓阳
 * @version 2017-03-14
 */
@Service
@Transactional(readOnly = true)
public class  OutpTreatRecService extends CrudService<OutpTreatRecDao, OutpTreatRec> {
    @Autowired
    private ClinicItemDictService clinicItemDictService;
    @Autowired
    private ClinicItemDictDao clinicItemDictDao;
    @Autowired
    private ExamApplyService commonService;
    @Autowired
    private OutpTreatRecDao outpTreatRecDao;
    @Autowired
    private ClinicVsChargeDao clinicVsChargeDao;
    @Autowired
    private TreatProjectItemDao treatProjectItemDao;
    @Autowired
    private ExpStockService expStockService;
    @Autowired
    private ExpStockDao expStockDao;
    @Autowired
    CompanyDao companyDao;
    @Autowired
    private ClinicOrdersDao clinicOrdersDao;
    @Autowired
    private ClinicMasterService clinicMasterService;
    @Autowired
    private OutpRcptMasterService outpRcptMasterService;
    @Autowired
    private ClinicMasterDao clinicMasterDao;
    @Autowired
    private PatMasterIndexDao patMasterIndexDao;
    @Autowired
    private HisDiagnosisDao hisDiagnosisDao;
    @Autowired
    private ClinicRecordDao clinicRecordDao;
    @Autowired
    private OrgDeptDao orgDeptDao;

    public OutpTreatRec get(String id) {
		return super.get(id);
	}
	
	public List<OutpTreatRec> findList(OutpTreatRec outpTreatRec) {
		return super.findList(outpTreatRec);
	}
	
	public Page<OutpTreatRec> findPage(Page<OutpTreatRec> page, OutpTreatRec outpTreatRec) {
		return super.findPage(page, outpTreatRec);
	}
    public Page<OutpTreatRec> TJfindList(Page<OutpTreatRec> page, OutpTreatRec outpTreatRec) {
            return super.findPage(page, outpTreatRec);
        }

    /**
     * 保存处置治疗
     * @param outpTreatRec
     * @return
     */
	@Transactional(readOnly = false)
	public String saveOutpTreatRec(OutpTreatRec outpTreatRec) {
        List<SaveDataVo> list=new ArrayList<SaveDataVo>();
        //clinicId  patientId || performedBy num ||  clinicItemDictId
        ClinicItemDict clinicItemDict=this.clinicItemDictService.get(outpTreatRec.getClinicItemId());
        double price=clinicItemDictDao.findPriceById(clinicItemDict.getId());
        SaveDataVo saveDataVo=new SaveDataVo();
        saveDataVo.setPatientId(outpTreatRec.getPatientId());
        saveDataVo.setItemName(clinicItemDict.getItemName());
        saveDataVo.setImplementDept(outpTreatRec.getImplementDept());
        saveDataVo.setChargeFlag("0");
        saveDataVo.setConfirmFlag("0");
        saveDataVo.setUnitsStr(outpTreatRec.getUnitsStr());
        saveDataVo.setPackageSpec(outpTreatRec.getPackageSpec());
        saveDataVo.setSupplierName(outpTreatRec.getSupplierName());
        saveDataVo.setClinicId(outpTreatRec.getClinicId());
//        Integer amount=clinicVsChargeDao.findByClinicId(clinicItemDict.getId());
        saveDataVo.setNum(Integer.parseInt(outpTreatRec.getNum()));
        saveDataVo.setClinicItemId(clinicItemDict.getId());
        saveDataVo.setApplyId("");
        saveDataVo.setSumPrice(price*(Integer.parseInt(outpTreatRec.getNum())));
        saveDataVo.setItemClass(clinicItemDict.getItemClass());
        saveDataVo.setIsApply("0");
        saveDataVo.setApplyNo(NumberUtils.getClinicTreat(outpTreatRec.getClinicId()));
        saveDataVo.setRcptNo("");//收费号
        saveDataVo.setImplementUser("");//执行人
        saveDataVo.setInoroutFlag("0");
        ClinicMaster clinicMaster=clinicMasterService.get(outpTreatRec.getClinicId());
        saveDataVo.setApplyDept(clinicMaster.getDeptId());
        list.add(saveDataVo);
        Map<String,Object> map= commonService.commonSave(list);
        String returnVal= map.get("treatId")+"";
        return returnVal;
  	}
	
	@Transactional(readOnly = false)
	public int delete(OutpTreatRec outpTreatRec) {
		return this.commonService.commonDel(outpTreatRec.getOrdersId());

	}

    /**
     * 根据门诊医嘱Id 删除处置治疗
     * @param clinicOrdersId
     * @return
     * @author 陈晓阳
     */
    @Transactional(readOnly = false)
    public int deleteByOrdersId(String clinicOrdersId) {
        return this.outpTreatRecDao.deleteByOrdersId(clinicOrdersId);
    }


    /**
     * 退费
     * @param outpTreatRec
     * @return
     */
    @Transactional(readOnly = false)
    public int refundIng(OutpTreatRec outpTreatRec){
        int num = outpTreatRecDao.refundIng(outpTreatRec);
        return num;
    }

    /**
     * 模板插入保存
     * @param id
     * @param clinicId
     * @return
     */
    @Transactional(readOnly = false)
    public String saveTreatTemplate(String id,String clinicId,String patientId,List<OutpTreatRec> list){
        String num = "";

        for(int i=1;i<list.size();i++){
            OutpTreatRec outpTreatRec = list.get(i);
            outpTreatRec.setClinicId(clinicId);
            outpTreatRec.setPatientId(patientId);
            outpTreatRec.setInoroutFlag("0");
            outpTreatRec.setConfirmFlag("0");
            outpTreatRec.setChargeFlag("0");
            outpTreatRec.setIsApply("1");
            num +=saveOutpTreatRec(outpTreatRec);
        }
        return num+"";
    }

    /**
     * 门诊消耗品待发list
     * @param outpTreatRec
     * @return
     * @author ZhuQ
     */
    public Page<OutpTreatRec> findByExp(Page<OutpTreatRec> page, OutpTreatRec outpTreatRec) {
        outpTreatRec.updateOrgId();
        outpTreatRec.setInoroutFlag("0");
        outpTreatRec.setChargeFlag("1");
        outpTreatRec.setItemClass("I");
        outpTreatRec.setImplementDept(null!=UserUtils.getUser().getOrgDept()?UserUtils.getUser().getOrgDept().getId():"");
//        outpTreatRec.setImplementDept("b7f5bf886e9140d099ec4d6baf8c87f8");
        outpTreatRec.setPage(page);
        page.setList(dao.findByExp(outpTreatRec));
        return page;
    }

    /**
     * 门诊消耗品已发人员list
     * @param outpTreatRec
     * @return
     * @author ZhuQ
     */
    public Page<OutpTreatRec> findByOutExp(Page<OutpTreatRec> page, OutpTreatRec outpTreatRec) {
        outpTreatRec.updateOrgId();
        outpTreatRec.setInoroutFlag("0");
        outpTreatRec.setChargeFlag("1");
        outpTreatRec.setItemClass("I");
        outpTreatRec.setConfirmFlag("1");
        outpTreatRec.setImplementDept(null!=UserUtils.getUser().getOrgDept()?UserUtils.getUser().getOrgDept().getId():"");
        outpTreatRec.setPage(page);
        page.setList(dao.findByOutExp(outpTreatRec));
        return page;
    }

    /**
     * 未发放的消耗品的list查询
     * @param outpTreatRec
     * @return
     */
    public List<ExpStock> expOutList(OutpTreatRec outpTreatRec) {
        String storageId=UserUtils.getUser().getOrgDept().getId();
        List<ExpStock> expStockList = expStockDao.expListOut(outpTreatRec.getPatientId(),outpTreatRec.getClinicId(), storageId);
        return expStockList;
    }


    /**
     * 已发放的消耗品list查询
     * @param outpTreatRec
     * @return
     */
    public List<ExpStock> expGiveOutList(OutpTreatRec outpTreatRec) {
        String storageId=UserUtils.getUser().getOrgDept().getId();
        List<ExpStock> expStockList = expStockDao.expListGiveOut(outpTreatRec.getPatientId(),outpTreatRec.getClinicId(), storageId);
        return expStockList;
    }



    @Transactional(readOnly = false)
    public String clinicExpOut(OutpTreatRec outpTreatRec) {
        String storageId=UserUtils.getUser().getOrgDept().getId();

        //根据包装规格比较实际上要发的小包装消耗品list
        List<ExpStock> expOutList = expStockDao.expListOutBySpec(outpTreatRec.getPatientId(),outpTreatRec.getClinicId(), storageId);
        int num=1;
        //定义库存量不够的消耗品名称
        String expName="";
        for(int i=0;i<expOutList.size();i++){
            //判断当前库房库存量是否够发药
            List <ExpStock> expStockQuantity = expStockDao.findByQuantity(expOutList.get(i));
            if(expStockQuantity.size()<1 || expStockQuantity.get(0).getQuantity()< expOutList.get(i).getQuantity() ){
                expName=expOutList.get(i).getExpName();
                return expName;
            }
        }

        for(int i=0;i<expOutList.size();i++){
            List<ExpStock> listByExpireDate = expStockDao.findByExpireDate(expOutList.get(i));
            //药库需要扣的数量
            Double quantityOut=expOutList.get(i).getQuantity();
            for(int j=0;j<listByExpireDate.size();j++){
                ExpStock expStock1=listByExpireDate.get(j);
                //if一个批次不够扣库存else一个批次够扣完
                if(quantityOut>listByExpireDate.get(j).getQuantity() && quantityOut>0){
                    expStock1.setQuantity(0.00);
                    expStock1.preUpdate();
                    num=num*expStockDao.update(expStock1);
                    quantityOut=quantityOut-listByExpireDate.get(j).getQuantity();
                }else if(quantityOut <= listByExpireDate.get(j).getQuantity() && quantityOut>0 ) {
                    expStock1.setQuantity(listByExpireDate.get(j).getQuantity()-quantityOut);
                    quantityOut=0.0;
                    expStock1.preUpdate();
                    num=num*expStockDao.update(expStock1);
                }
            }

            //修改 处置治疗表的发放状态
            ClinicOrders clinicOrders=clinicOrdersDao.get(expOutList.get(i).getOrdersId());
            clinicOrders.setImplementDept(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
            clinicOrders.setImplementUser(null != UserUtils.getUser().getId() ? UserUtils.getUser().getId() : "");
            clinicOrders.preUpdate();
            num=num*clinicOrdersDao.update(clinicOrders);

            OutpTreatRec outpTreatRec1=dao.get(expOutList.get(i).getTreatId());
            outpTreatRec1.setConfirmFlag("1");
            outpTreatRec1.setRemarks("已发放");
            outpTreatRec1.preUpdate();
            num=num*dao.update(outpTreatRec1);
        }
        return num+"";
    }

    /**
     * 门诊处方退药
     * @param outpTreatRec
     * @return
     * @author ZhuQ
     */
    @Transactional(readOnly = false)
    public String clinicExpIn(OutpTreatRec outpTreatRec){
        int num=1;

        //根据prescriptionApply的Id获取要退的库存list
        List<ExpStock> expOutList = expStockDao.expListInBySpec(outpTreatRec.getId());
        for(int i=0;i<expOutList.size();i++){
            List<ExpStock> listByExpireDate = expStockDao.findByExpireDate(expOutList.get(i));
            //药库需要加的数量：加到保质期最近的一批药上，以便下次发药时先出
            Double quantityOut=expOutList.get(i).getQuantity();
            ExpStock expStock1=listByExpireDate.get(0);
            expStock1.setQuantity(expStock1.getQuantity()+ quantityOut );
            expStock1.preUpdate();
            num=num*expStockDao.update(expStock1);

            //修改 处置治疗表的发放状态
            ClinicOrders clinicOrders=clinicOrdersDao.get(expOutList.get(i).getOrdersId());
            clinicOrders.setImplementDept(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
            clinicOrders.setImplementUser(null != UserUtils.getUser().getId() ? UserUtils.getUser().getId() : "");
            clinicOrders.setChargeFlag("3");
            clinicOrders.preUpdate();
            num=num*clinicOrdersDao.update(clinicOrders);

            String rcptNo = clinicOrders.getRcptNo();
            String chargeFlag="3";
            outpRcptMasterService.updateChargeFlag(rcptNo,chargeFlag, UserUtils.getOrgId());

            OutpTreatRec outpTreatRec1=dao.get(expOutList.get(i).getTreatId());
            outpTreatRec1.setChargeFlag("3");
            outpTreatRec1.setRemarks("已退");
            outpTreatRec1.preUpdate();
            num=num*dao.update(outpTreatRec1);
        }
        return num+"";
    }
    /**
     * 处置治疗单打印
     * @param
     * @param
     * @return String
     * @author 樊多
     */
    public String outpTreatRecPrint(String ids,String clinicId,String patientId){
        User user = UserUtils.getUser();
        Map map = new HashMap();
        List list = new ArrayList();
        String printPath = "";
        double total=0;
        String [] id = ids.split(",");
        for(int i = 0;i<id.length;i++) {
            list.add(outpTreatRecDao.findAsDto(id[i]));
            total=Double.parseDouble(outpTreatRecDao.findAsDto(id[i]).get("sumPrice").toString()) + total;
        }
        PatMasterIndex patMasterIndex= patMasterIndexDao.get(patientId);
        ClinicMaster clinicMaster=clinicMasterDao.get(clinicId);
        List<BaseDto> hisDiagnosis=hisDiagnosisDao.findIcdNameByClinicId(clinicId);
        String icdName="";
        for(BaseDto baseDto:hisDiagnosis){
            icdName=icdName+(String)baseDto.get("icdName")+",";
        }
        ClinicRecord clinicRecord=clinicRecordDao.getRecordByClinicId(clinicId, patientId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Company company=companyDao.get(user.getOrgId());
        map.put("name",patMasterIndex.getName());//姓名
        String sex= DictUtils.getDictLabel(patMasterIndex.getSex(), "SEX_DICT", "");
        map.put("sex",sex);
        map.put("age",patMasterIndex.getAge());
        map.put("clinicNo",clinicMaster.getClinicNo());
        if(clinicRecord!=null) {
            map.put("zhusu", LongTextToString.unescape(clinicRecord.getZhusu()));
            map.put("xianbingshi",LongTextToString.unescape(clinicRecord.getXianbingshi()));
            map.put("tijian", LongTextToString.unescape(clinicRecord.getTigejiancha()));
            map.put("icdName", icdName);
            map.put("suggestion",LongTextToString.unescape(clinicRecord.getSuggestion()));
            map.put("treatmentProject","");
        }
        map.put("total",total);
        map.put("hospital",user.getCompany().getOrgName());
        map.put("userName",user.getName());
        OrgDept orgDept=orgDeptDao.get(clinicMaster.getDeptId());
        map.put("deptName",orgDept.getDeptName());//就诊科室
        map.put("deptLocation",orgDept.getRemarks());//科室位置
        Calendar calendar =Calendar.getInstance();
        calendar.setTime(new Date());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day=calendar.get(Calendar.DAY_OF_MONTH);
        map.put("date",year+"-"+month+"-"+day);
        printPath = PrintPdfUtils.previewPdf(user.getId(),"his/outpTreatRecPrint.jasper", map, list, "outpTreatRecPrint");
        return printPath;
    }
}